import React from 'react';
const CryptoJS = require('crypto-js'); //引用AES源码js
encode();
let key_ = '';
let iv_ = '';
export async function encode(data, ciphertext) {
  if (!(key_ && iv_)) {
    const res = await window.g_app._store.dispatch({
      type: 'login/getAeskey',
    });
    if (res) {
      key_ = (res.msg || '').substring(32, 48);
      iv_ = (res.msg || '').substring(80);
    }
  }
  if (!data) {
    return '';
  }
  const key = CryptoJS.enc.Utf8.parse(key_); //十六位十六进制数作为密钥
  const iv = CryptoJS.enc.Utf8.parse(iv_); //十六位十六进制数作为密钥偏移量
  let srcs = CryptoJS.enc.Utf8.parse(data);
  let encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC });
  // let encrypted = CryptoJS.TripleDES.encrypt(srcs, key, );
  return encrypted.toString();
}

// let encrypted = CryptoJS.TripleDES.encrypt(srcs, key, );
// return { key_, iv_ };
export async function decode(data, ciphertext) {
  if (!(key_ && iv_)) {
    const res = await window.g_app._store.dispatch({
      type: 'login/getAeskey',
    });
    if (res) {
      key_ = (res.msg || '').substring(32, 48);
      iv_ = (res.msg || '').substring(80);
    }
  }
  if (!data) {
    return '';
  }
  const key = CryptoJS.enc.Utf8.parse(key_); //十六位十六进制数作为密钥
  const iv = CryptoJS.enc.Utf8.parse(iv_); //十六位十六进制数作为密钥偏移量
  var decrypted = CryptoJS.AES.decrypt(data, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
  });
  return decrypted.toString(CryptoJS.enc.Utf8);

  //
  // let srcs = CryptoJS.enc.Utf8.parse(data);
  // let encrypted = CryptoJS.AES.decrypt(srcs, key, {iv: iv, mode: CryptoJS.mode.CBC});
  // console.error("encrypted.toString()"+encrypted.toString());
  // return encrypted.toString();
  //
}
